package com.zmj.exception;

import com.zmj.common.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 *
 * @author zmj
 * @date 2021-08-27 10:31
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理系统异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseVO systemErrorHandler(Exception e) {
        return ResponseVO.build(e);
    }

    /**
     * 处理自定义全局异常
     */
    @ExceptionHandler(value = CustomizeException.class)
    public ResponseVO customizeException(CustomizeException e) {
        return ResponseVO.error(e.getCode(), e.getMsg());
    }


    /**
     * Validated 参数校验全局异常处理器
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public ResponseVO MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                log.warn("Bad Request Parameters: req entity [{}],message [{}]", fieldError.getObjectName(), fieldError.getDefaultMessage());
                stringBuilder.append(fieldError.getDefaultMessage());
            });
        }
        return ResponseVO.error(stringBuilder.toString());
    }

}
